package com.example.security;

import cn.hutool.json.JSONUtil;
import com.example.common.result.Result;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
//拒绝访问处理器
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        //设置返回类型和字符编码
        response.setContentType("application/json;charset=UTF-8");
        //设置权限不足状态码
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        //定义一个response输出流
        ServletOutputStream outputStream = response.getOutputStream();

        //将异常消息封装成Result
        Result result = Result.error().message("权限不足").code(HttpServletResponse.SC_FORBIDDEN);

        //将result写入输出流中
        outputStream.write(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));
        //刷新此输出流并强制写出所有缓冲的输出字节
        outputStream.flush();
        //将输出流关闭
        outputStream.close();
    }
}
